package admin

import (
	"context"
	"errors"
	"fmt"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type CategorySaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCategorySaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CategorySaveLogic {
	return &CategorySaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CategorySaveLogic) CategorySave(req *types.CategorySaveReq) (resp string, err error) {

	data := &models.Category{
		ParentID: req.ParentID,
		Name:     req.Name,
	}

	check := utils.GetData(data)

	if (check && req.Id == 0) || (check && req.Id != data.ID) {
		return "", errors.New("类目名称已存在")
	}

	copier.Copy(data, req)

	if req.Id == 0 {
		if check {
			return "", errors.New("类目名称已存在")
		}
		err = utils.InsertData(data)
		req.Id = data.ID
	}
	if req.ParentID == 0 {
		data.Level = fmt.Sprintf(",%d,%d", data.ID, data.SortOrder)
	} else {
		data.Level = fmt.Sprintf(",%d,%d,%d", req.ParentID, data.SortOrder, req.Id)
	}
	err = utils.UpdateById(req.Id, data)

	if err != nil {
		return "", err
	}

	return "操作成功", nil
}
